import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PwdSetDialog extends StatefulWidget {
  const PwdSetDialog({Key key}) : super(key: key);

  @override
  _PwdSetDialogState createState() => _PwdSetDialogState();
}

enum UserInputStatus{
  //校验身份中
  VALID_USER,
  //校验身份失败
  VALID_FAIL,
  //输入密码中
  IN_INPUT_PWD,
  //再次输入密码中
  IN_INPUT_AGAIN,
  //两次输入的密码不同
  INPUT_PWD_DIFF,
  //两次输入的密码相同
  INPUT_PWD_SAME
}

class _PwdSetDialogState extends State<PwdSetDialog> {

  static const MAX_COUNT = 6;

  UserInputStatus _inputStatus = UserInputStatus.IN_INPUT_PWD;

  List _unlockPwd = [];

  List _unlockPwdAgain = [];

  @override
  Widget build(BuildContext ctx) {
    _updateStatus();
    return SingleChildScrollView(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.0),
            decoration: BoxDecoration(
              color:_inputStatus == UserInputStatus.INPUT_PWD_DIFF?Colors.red:Colors.blueAccent,
            ),
            child: Center(
              child: _titleText(ctx)
            ),
          ),
          Container(
              height: 100,
              width: double.infinity,
              decoration: BoxDecoration(
                  color: Color(0xffeeeeee),
              ),
              alignment: Alignment.center,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    height:30,
                    child: ListView.builder(
                        shrinkWrap: true,
                        physics:NeverScrollableScrollPhysics(),
                        itemCount: MAX_COUNT,
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (ctx,index){
                          return Container(
                            alignment: Alignment.center,
                            child: AnimatedCrossFade(
                              duration: Duration(milliseconds: 300),
                              crossFadeState:_unlockPwd.length <= index ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                              firstChild: Icon(Icons.panorama_fish_eye,size: 20,),
                              secondChild: Icon(Icons.circle,size: 20,),
                            ),
                          );
                        }
                    ),
                  ),
                  _unlockPwd.length == MAX_COUNT?
                  SizedBox(
                    height: 30,
                    child: ListView.builder(
                        shrinkWrap: true,
                        physics:NeverScrollableScrollPhysics(),
                        itemCount: MAX_COUNT,
                        scrollDirection: Axis.horizontal,
                        itemBuilder: (ctx,index){
                          return Container(
                            alignment: Alignment.center,
                            child: AnimatedCrossFade(
                              duration: Duration(milliseconds: 300),
                              crossFadeState:_unlockPwdAgain.length <= index ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                              firstChild: Icon(Icons.panorama_fish_eye,size: 20,),
                              secondChild: Icon(Icons.circle,size: 20,),
                            ),
                          );
                        }
                    ),
                  ):Container()
                ],
              )
          ),
          Container(
            child: _keyboard(ctx),
          )
        ],
      ),
    );
  }

  Widget _titleText(ctx){
    switch(_inputStatus){
      case UserInputStatus.IN_INPUT_PWD:
        return Text('输入密码',style: TextStyle(fontSize: 20,color: Colors.white),);
      case UserInputStatus.IN_INPUT_AGAIN:
        return Text('再次输入密码',style: TextStyle(fontSize: 20,color: Colors.white),);
      case UserInputStatus.INPUT_PWD_DIFF:
        return Text('两次输入的密码不同',style: TextStyle(fontSize: 20,color: Colors.white),);
      case UserInputStatus.INPUT_PWD_SAME:
        return Text('保存成功',style: TextStyle(fontSize: 20,color: Colors.white),);
      case UserInputStatus.VALID_FAIL:
        return Text('验证失败',style: TextStyle(fontSize: 20,color: Colors.white),);
      case UserInputStatus.VALID_USER:
        return Text('请输入旧密码',style: TextStyle(fontSize: 20,color: Colors.white),);
    }
  }

  _updateStatus(){
    if(_unlockPwdAgain.length == MAX_COUNT){
      bool isDiff = false;
      for(int i =0;i<MAX_COUNT;i++){
        if(_unlockPwd[i]!=_unlockPwdAgain[i]){
          isDiff = true;
          break;
        }
      }
      setState(() {
        if(isDiff){
          _inputStatus = UserInputStatus.INPUT_PWD_DIFF;
        }else{
          _savePwd();
          _inputStatus = UserInputStatus.INPUT_PWD_SAME;
        }
      });
      return;
    }
    if(_unlockPwd.length == MAX_COUNT){
      setState(() {
        _inputStatus = UserInputStatus.IN_INPUT_AGAIN;
      });
    }else{
      setState(() {
        _inputStatus = UserInputStatus.IN_INPUT_PWD;
      });
    }
  }

  Widget _keyboard(ctx){
      return GridView(
        shrinkWrap: true,
        physics:NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 0.0,
            mainAxisSpacing: 0.0,
            childAspectRatio: 1.75
        ),
        children: [
          _createGridViewItem('1',ctx),
          _createGridViewItem('2',ctx),
          _createGridViewItem('3',ctx),
          _createGridViewItem('4',ctx),
          _createGridViewItem('5',ctx),
          _createGridViewItem('6',ctx),
          _createGridViewItem('7',ctx),
          _createGridViewItem('8',ctx),
          _createGridViewItem('9',ctx),
          _createBtnGridViewItem(Icons.clear,(){
            setState(() {
              _unlockPwd.clear();
              _unlockPwdAgain.clear();
            });
          }),
          _createGridViewItem('0',ctx),
          _createBtnGridViewItem(Icons.delete,(){
            setState(() {
              if(_unlockPwdAgain.isNotEmpty){
                _unlockPwdAgain.removeLast();
              }else{
                if(_unlockPwd.isNotEmpty){
                  _unlockPwd.removeLast();
                }
              }
            });
          })
        ],
      );
  }

  Widget _createGridViewItem(String number,BuildContext ctx){
    return  Ink(
        decoration: BoxDecoration(
            color: Color(0xfff5f5f5),
          border: Border.all(color: Color(0xffdcdcdc), width: 0.25),//边框
        ),
        child:  InkWell(
            splashColor: Colors.blueAccent,
            onTap: () {
              if(_unlockPwdAgain.length == MAX_COUNT){
                return;
              }
              if(_unlockPwd.length == MAX_COUNT){
                setState(() {
                  _unlockPwdAgain.add(number);
                });
              }else{
                setState(() {
                  _unlockPwd.add(number);
                });
              }
            },
            child: Center(
              child: Text(number,style: TextStyle(fontSize: 18.0)),
            )
        )
    );
  }

  _createBtnGridViewItem(IconData icon,onTap){
    return Ink(
      decoration: BoxDecoration(
          color: Colors.blueAccent,
        border: Border.all(color: Color(0xffdcdcdc), width: 0.25),//边框
      ),
      child:  InkWell(
        onTap: onTap,
        child: Center(
            child: Icon(icon,size: 30,color: Colors.white)
        ),
      ),
    );
  }

  _savePwd()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var pwdStr = _unlockPwdAgain.join('');
    await prefs.setString('_unlock_pwd', pwdStr);
  }


}
